<template>
  <el-card class="box-card">
    <!-- 头部 面包屑 -->

    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 内容主题部分  -->

    <el-row :gutter="10">
      <el-col :span="12"
        ><div class="grid-content bg-purple">
          <!-- @keydown.native.enter="getUserList" -->
          <el-input
            placeholder="请输入内容"
            v-model="query"
            class="input-with-select"
            @clear="getUserList"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </div>
      </el-col>
      <el-col :span="4">
        <!-- @click="addDialogForm=true" -->
        <div class="grid-content bg-purple">
          <el-button type="primary" @click="addDialogForm">添加用户</el-button>
        </div>
      </el-col>
    </el-row>

    <!--  列表展示 -->

    <el-table :data="tableData" border stripe style="width: 100%">
      <!--  需要注意一下 type =index -->
      <el-table-column label="#" width="50" type="index"> </el-table-column>

      <el-table-column prop="username" label="姓名" width="180" height="50">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"> </el-table-column>

      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column prop="role_name" label="角色"> </el-table-column>
      <el-table-column prop="mg_state" label="状态">
        <!-- https://element.eleme.cn/#/zh-CN/component/table  自定义的table -->
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeStatus(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column prop="address" label="操作" class="ctrolBox">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-share"
            @click="editeUsers(scope)"
            >修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="deleteUsers(scope)"
            >删除</el-button
          >

          <el-tooltip
            class="item"
            effect="dark"
            content="分配权限"
            placement="top"
          >
            <el-button
              type="warning"
              icon="el-icon-setting"
              @click="modifyUsers(scope)"
              >操作权限</el-button
            >
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!--  添加用户弹框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogFormVisible"
      center
      width="50%"
    >
      <el-form :model="addform" ref="addform" :rules="rules">
        <el-form-item
          label="用户名"
          :label-width="addFormLabelWidth"
          prop="username"
        >
          <el-input v-model="addform.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="addFormLabelWidth"
          prop="password"
        >
          <el-input v-model="addform.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          :label-width="addFormLabelWidth"
          prop="email"
        >
          <el-input v-model="addform.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
          :label-width="addFormLabelWidth"
        >
          <el-input v-model="addform.mobile" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item>
          <div class="addUserBtn">
            <el-button type="primary" @click="resetForm('addform')"
              >取消</el-button
            >

            <el-button
              type="primary"
              @click="submitForm('addform')"
              class="login-btn"
              >确定</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--  编辑用户 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editeDialogFormVisible"
      center
      width="50%"
    >
      <el-form :model="editeform" ref="editeform" :rules="rules">
        <el-form-item
          label="用户名"
          :label-width="editeFormLabelWidth"
          prop="username"
        >
          <el-input
            v-model="editeform.username"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <!-- <el-form-item
          label="密码"
          :label-width="editeFormLabelWidth"
          prop="password"
        >
          <el-input v-model="editeform.password" autocomplete="off"></el-input>
        </el-form-item> -->
        <el-form-item
          label="邮箱"
          :label-width="editeFormLabelWidth"
          prop="email"
        >
          <el-input v-model="editeform.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
          :label-width="editeFormLabelWidth"
        >
          <el-input v-model="editeform.mobile" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item>
          <div class="addUserBtn">
            <el-button type="primary" @click="editeDialogFormVisible = false"
              >取消</el-button
            >

            <el-button
              type="primary"
              @click="editeSubmitForm('editeform')"
              class="login-btn"
              >确定</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配权限 弹框  -->

    <el-dialog title="分配角色" :visible.sync="grantDialogFormVisible">
      <el-form :model="grantForm" label-width="120px">
        <el-form-item label="当前的用户：" prop="username">
          <el-tag type="info">{{ grantForm.username }}</el-tag>
        </el-form-item>
        <el-form-item label="请选择角色：">
          <el-select v-model="roleId" placeholder="请选择角色">
            <el-option
              v-for="(role, index) in roleList"
              :key="index"
              :label="role.roleName"
              :value="role.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantUserSubmit()">确 定</el-button>
      </div>
    </el-dialog>

    <!--  分页  -->

    <!-- 分页组件用法：
① 当前页码：pagenum
② 每页条数：pagesize
③ 记录总数：total
④ 页码变化事件
⑤ 每页条数变化事件
⑥ 分页条菜单控制 -->

    <el-pagination
      class="page"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[2, 3, 5, 10]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </el-card>
</template>

<script>
// 面包屑导航 el-breadcrumb
// Element-UI 栅格系统基本使用 el-row
// 表格布局 el-table、el-pagination
var id = "";

export default {
  name: "",
  components: {},
  props: {},
  data() {
    //自定义验证邮箱
    var validateEmail = (rule, value, callback) => {
      console.log(value);
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      }
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      var flagEmail = regEmail.test(value);

      if (!flagEmail) {
        return callback(new Error("输入的邮箱格式不符合规则"));
      }
      // this.$message.success("邮箱验证通过");
      callback();
    };

    //自定义验证手机号码
    var validateMobile = (rule, value, callback) => {
      console.log(value);
      if (!value) {
        return callback(new Error("手机号不能为空"));
      }
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      var flagMobile = regMobile.test(value);

      if (!flagMobile) {
        return callback(new Error("输入的手机号码不符合规则"));
      }
      // this.$message.success("手机号码验证通过");
      callback();
    };

    return {
      query: "",
      total: 0, // 总数量
      pagenum: 1, //当前页码
      pagesize: 1, //每页条数：pagesize
      // currentPage: 1,

      tableData: [
        {
          username: "admin",
          mobile: "18616358651",
          type: 1,
          email: "tige112@163.com",
          create_time: "2017-11-09T20:36:26.000Z",
          mg_state: true, // 当前用户的状态
          role_name: "炒鸡管理员",
        },
      ],
      //添加用户弹框的属性
      addDialogFormVisible: false,
      addFormLabelWidth: "120px",
      addform: {
        username: "添加",
        mobile: "13288888888",
        password: "123456",
        email: "123@qq.com",
      },
      rules: {
        //  系统提供的验证用户名与密码

        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" },
        ],
        //自定义验证 邮箱与手机号码
        email: [{ validator: validateEmail, trigger: "blur" }],
        mobile: [{ validator: validateMobile, trigger: "blur" }],
      },

      // 编辑用户弹框属性
      editeDialogFormVisible: false, //
      editeFormLabelWidth: "120px",
      editeform: {
        username: "编辑",
        mobile: "13288888888",
        // password: "123456",
        email: "123@qq.com",
      },

      // 分配权限 弹框属性
      grantDialogFormVisible: false,
      grantForm: {
        username: "分配权限",
      },
      roleId: "技术负责人",
      roleList: [], // 角色列表
    };
  },
  computed: {},
  watch: {
    query(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.getUserList();
      }
    },
  },
  created() {
    this.getUserList();
  },
  mounted() {},
  methods: {
    //获取用户列表

    async getUserList() {
      //  var params={query: this.query}
      var params = {
        query: this.query,
        pagenum: this.pagenum,
        pagesize: this.pagesize,
      };
      // 解构赋值重新命名 data=>res
      let { data: res } = await this.$http.get("users", { params: params });

      console.log("getUserList", res);

      if ((res.meta.status = !200)) {
        return this.$message.error("请求数据失败");
      }
      this.tableData = res.data.users;
      this.total = res.data.total;
      this.pagenum = res.data.pagenum;
    },

    // 当前多少条数据  //显示当前每页的条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pagesize = val;
      this.getUserList();
    },

    //  当前显示哪一页数据
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pagenum = val;
      this.getUserList();
    },

    //  编程改变用户状态的方法
    // 开关组件的用法
    // 接口调用更改用户的状态
    async changeStatus(row) {
      console.log(row);
      let { id, mg_state } = row;
      // users/:uId/state/:type
      var url = `users/${id}/state/${mg_state}`;
      let { data: res } = await this.$http.put(url);
      if (res.meta.status == 200) {
        this.$message.success(res.meta.msg);
        this.getUserList();
      }
    },

    // 5.4 用户管理-添加用户
    addDialogForm() {
      //  1  添加用户表单弹窗布局
      this.addDialogFormVisible = true;
      // 2    弹窗组件用法
      // 3   控制弹窗显示和隐藏
    },

    //取消
    resetForm() {
      this.addDialogFormVisible = false;
    },

    //添加提交数据
    submitForm(formName) {
      // 验证

      this.$refs[formName].validate(async (valid) => {
        console.log(valid);
        if (!valid) return this.$message.error("用户书写的不规范");

        let { data: res } = await this.$http.post("users", this.addform);

        //  console.log('addform',res)

        if (res.meta.status == 201) {
          this.$message.success(res.meta.msg);
        }

        // 关闭弹框
        this.addDialogFormVisible = false;

        //重新获取用户列表

        this.getUserList();
      });
    },

    // 用户管理-编辑用户
    //  根据 ID 查询用户信息
    //create_time: 1623057209
    // email: "123@qq.com"
    // id: 513
    // mg_state: true
    // mobile: "13288888888"
    // role_name: "超级管理员"
    // username: "貂蝉小姐姐好"

    async editeUsers(scope) {
      //打开编辑用户弹框
      this.editeDialogFormVisible = true;

      console.log(scope.row);
      let { id, password } = scope.row;

      let { data: res } = await this.$http.get(`users/${id}`);
      if (res.meta.status == 200) {
        this.$message.success(res.meta.msg);

        var { email, mobile, username, id: editId } = res.data;

        console.log(email);
        console.log(username);
        console.log(mobile);
        console.log(editId);
        this.editeform = { email, username, mobile, id: editId };
      }
    },

    //编辑用户数据
    editeSubmitForm(editeform) {
      this.$refs[editeform].validate(async (valid) => {
        // console.log(   '编辑验证',valid);

        // console.log( this.editeform)
        let { mobile, email, id } = this.editeform;

        if (!valid) return this.$message.error("编程用户书写的不规范");

        // //编辑数据请求
        // // id用户
        // // email
        // // mobile
        var url = `users/${id}`;

        let { data: res } = await this.$http.put(url, { email, mobile });

        console.log("editeform", res);

        if (res.meta.status == 200) {
          this.$message.success(res.meta.msg);
        }

        // // 关闭弹框
        this.editeDialogFormVisible = false;

        // //重新获取用户列表

        this.getUserList();
      });
    },

    //删除用户
    async deleteUsers(scope) {
      let {
        row: { id },
      } = scope;
      // console.log("deleteUsers", row);

      //  this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      // .then(  async () => {
      //   this.$message({
      //     type: 'success',
      //     message: '删除成功!'
      //   });
      //   let {data:res} = await this.$http.delete(`users/${id}`)

      // })
      // .catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消删除'
      //   });
      // });

      let confirmRes = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => {
        console.log("错误", err);
      });

      // console.log(confirmRes);  // 取消的undefinde   确认是 confirm
      if (!confirmRes)
        return this.$message({ type: "info", message: "已取消删除" });

      // 删除成功
      let { data: res } = await this.$http.delete(`users/${id}`);

      if (res.meta.status == 200) this.$message.success(res.meta.msg);
      // //重新获取用户列表
      this.getUserList();
    },

    //     完成分配用户角色功能
    // 分配角色按钮添加事件,并使用弹窗组件

    async modifyUsers(scope) {
      console.log(scope.row);
      id = scope.row.id;

      this.roleId = scope.row.role_name;

      this.grantForm.username = scope.row.username;
      // 打开分配角色的弹框
      this.grantDialogFormVisible = true;

      // 获取角色列表
      let { data: resRoleList } = await this.$http.get("roles");
      console.log("resRoleList", resRoleList);
      this.roleList = resRoleList.data;
    },

    //分配角色确定提交事件处理
    async grantUserSubmit() {
      //  查询角色
      // roles/:id
      let { data: resRole } = await this.$http.put(`users/${id}/role`, {
        rid: this.roleId,
      });

      console.log("resRole", resRole);

      //最近提交后需要关闭弹框
      this.grantDialogFormVisible = false;
      this.getUserList();
    },
  },
};
</script>

<style scoped  lang="less">
.ctrolBox {
  .el-button {
    font-size: 14px !important;
  }
}

.page {
  padding: 15px 0;
  // background-color: #D3DCE6;
}

.addUserBtn {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
